--桌子逻辑
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local tabletool = require "tabletool"
local timetool = require "timetool"
local timer = require "timer"
local filelog = require "filelog"
local configdao = require "configdao"
local base = require "base"
local json = require "cjson"
local yydbtool = require "yydbtool"
json.encode_sparse_array(true, 1, 1)

require "yydbenum"

local TableLogic = {}
local service = nil
local seatlogic = nil
local gamelogic = nil

function TableLogic.init(caller)
	service = caller
end

-- 在tablecmd:start 调用的
-- 这里的 tableobj，其实就是 table_data
-- conf 是从客户端传上来的, table_conf
--
function TableLogic.init_data(tableobj, conf, attachconf)
	-- 这里的两个logic 是tablelogic后面才加入进去的，所以没办法放到 init() 里面去初始化
	seatlogic = service:get_logicbyname("seatlogic")

	-- 获得游戏逻辑
	gamelogic = service:get_logicbyname("gamelogic")
	if conf == nil  then
		filelog.sys_error("TableLogic.init_data conf == nil", conf)
		return false
	end

    --初始化桌子信息
	local now = timetool.get_time()
    local nodename = skynet.getenv("nodename")
	tableobj.table_type = conf.table_type
	tableobj.uuid = nodename .. "_" .. attachconf.code .. "_" .. attachconf.index .. "_" .. now
	tableobj.index = attachconf.index
	tableobj.code = attachconf.code
	tableobj.state = YYDBTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
	tableobj.create_rid = attachconf.rid
	tableobj.create_rolename = attachconf.rolename
    tableobj.create_logo = attachconf.logo
	tableobj.create_time = now
	tableobj.cur_player_num = 0
	tableobj.curr_to_num = 0
	tableobj.conf = conf
    tableobj.cur_watch_playernum = 0
    tableobj.table_service = attachconf.table_service
    tableobj.sitdown_player_num = 0
    tableobj.agencylevel = attachconf.agencylevel            --代理等级，0表示非代理创建桌
    tableobj.table_persist = attachconf.table_persist        --桌子没人时，保留时间
    tableobj.tradeid = attachconf.tradeid
    tableobj.last_heart_time = now
    tableobj.level_type = attachconf.level_type or 1
    tableobj.min_player_num = 1             --桌子最小人数
    tableobj.max_history_record_num = 100   --保存的最大历史记录数量
    tableobj.sys_banker_info = TableLogic.gen_system_banker_info(tableobj)  --构建系统庄家信息
    tableobj.is_may_return_bet = false   --是否可能返还押注
    tableobj.service_fee_rate = 0.03    --服务费比率3%
    tableobj.special_seats_num = 6      --特权位数目

    --设置最小携带量
    if not tableobj.conf.min_carry_amount or tableobj.conf.min_carry_amount < 0 then
        tableobj.conf.min_carry_amount = 0
    end

    --设置最大携带量
    if not tableobj.conf.max_carry_amount or tableobj.conf.max_carry_amount < 0 then
        tableobj.conf.max_carry_amount = 0
    end

    --设置最大玩家数
    tableobj.conf.max_player_num = tableobj.conf.max_player_num or 500

    --初始化倍率列表
    local fmt_odds_list = skynet.call(".slotmgr", "lua", "get_format_odds_list") or {}
    tableobj.odds_list = {}
    for _,v in pairs(fmt_odds_list) do
        local id = math.floor(v / 100)
        local odds = v % 100
        tableobj.odds_list[id] = odds
    end
    --添加座位
	local seat
	local count = 1
	while count <= conf.max_player_num do
		seat = { }
        seatlogic.init_data(seat,count)
		table.insert(tableobj.seats, seat) --初始化座位数据
		count = count + 1
	end

    --初始游戏数据
	tableobj.gameobj = {tableobj = {}, stateevent = {}}
	gamelogic.init_data(tableobj.gameobj, tableobj)

	gamelogic.wait_player_sitdown(tableobj.gameobj)

	return true
end

---------------------------------------------------------
--处理客户端请求
--

--
-- 进桌
-- 客户端进桌请求最终在这里处理
-- tableobj：桌子对象
-- request：请求包
-- seat： 座位对象，nil or 非nil，由此判断是否重进桌子？
--
function TableLogic.entertable(tableobj, rid, roledata, request, seat)
    local playerinfo = roledata.info or {}
    local playermoney = roledata.money or {}

    --处理重进桌子
	if seat then
		local noticemsg = {
			rid = seat.rid,
			seat_index = seat.index,	
		}
		TableLogic.sendmsg_to_tableplayer(seat.rid,"reentertableN", noticemsg)
		if not tableobj.is_had_start then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
		end
	else    --新进入桌子

        --先加入等待玩家列表，并设置相关信息
		local waitinfo = tableobj.waits[rid]
        if waitinfo == nil then
			waitinfo = {}
			waitinfo.playerinfo = {}
			tableobj.waits[rid] = waitinfo
			tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1			 
        end

		waitinfo.rid = rid
        waitinfo.playerinfo.coin = playermoney.coin
        waitinfo.playerinfo.diamond = playermoney.diamond
        waitinfo.is_robot = roledata.is_robot
        --暂不支持旁观，超过10s未坐下，则踢出
        if not waitinfo.watch_timer_id then
            waitinfo.watch_timer_id = 0
            local curmoney = TableLogic.get_curmoney(waitinfo)
            waitinfo.watch_timer_id = timer.settimer(10 * 100,"do_watch",{rid = rid, coin = curmoney})
        end
	end

    --如果正在删除桌子，停止删除
	if tableobj.delete_table_timer_id > 0 then
		timer.cleartimer(tableobj.delete_table_timer_id)
		tableobj.delete_table_timer_id = -1
	end

    if not tableobj.is_had_start and tableobj.sitdown_player_num <= 0 then
        tableobj.state = YYDBTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
    end
end

--
--坐下
--
function TableLogic.sitdowntable(tableobj, rid, request, seat, roledata)
    local playerinfo = roledata.info or {}
    local playermoney = roledata.money or {}

    --清空旁观超时计时器
    local waitinfo = tableobj.waits[rid] or {}
    if waitinfo.watch_timer_id and waitinfo.watch_timer_id > 0 then
        timer.cleartimer(waitinfo.watch_timer_id)
    end
    tableobj.waits[rid] = nil
    tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1

    --初始化seat数据
	seat.rid = rid
	seat.playerinfo.rolename = playerinfo.rolename or ""
	seat.playerinfo.logo = playerinfo.logo or ""
	seat.playerinfo.sex = playerinfo.sex or 0
	seat.playerinfo.ip_addr = roledata.ip_addr or playerinfo.ip_addr
    seat.playerinfo.gps_addr = roledata.gps_addr or playerinfo.gps_addr
    seat.playerinfo.recommrid =  playerinfo.recommrid           --推荐人rid
	seat.playerinfo.agencyrid =  playerinfo.agencyrid           --代理rid
	seat.playerinfo.agencylevel =  playerinfo.agencylevel or 0  --代理等级，0表示不是代理
    seat.playerinfo.level = playerinfo.level or 0
    seat.playerinfo.intro = playerinfo.intro or ""
    seat.playerinfo.upvoted_num = playerinfo.upvoted_num
    seat.playerinfo.downvoted_num = playerinfo.downvoted_num
    seat.playerinfo.logoframe = playerinfo.logoframe

	seat.state = YYDBSeatState.SEAT_STATE_WAIT_READY
	seat.playerinfo.coin = playermoney.coin or 0
	seat.playerinfo.lock_coin = playermoney.lock_coin or 0
	seat.playerinfo.diamond = playermoney.diamond or 0
    seat.playerinfo.lock_diamond = playermoney.lock_diamond or 0
	seat.is_disconnected = false
    seat.is_robot = roledata.is_robot or false
    seat.cur_base_score = tableobj.conf.base_score_list[1] --默认选择第1个可选底注
    seat.get_code = ""

    local all_code_len = #tableobj.all_random_codes_pool
    if all_code_len > 0 then
        local get_index = base.get_random(1, all_code_len)
        local get_code = table.remove(tableobj.all_random_codes_pool, get_index)
        seat.get_code = get_code
        tableobj.rids_with_random_codes[get_code] = rid
    end

    --未开局
    if not tableobj.is_had_start or tableobj.state == YYDBTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN then
        tableobj.is_had_start = false
	    tableobj.state = YYDBTableState.TABLE_STATE_WAIT_ALL_READY
	    gamelogic.on_sitdown_table(tableobj.gameobj, seat)
    end

    seat.ready_to_time = seat.ready_to_time or 2        --测试
    seat.ready_timeout_time = timetool.get_time() + seat.ready_to_time

    --设置超时
    if not seat.ready_timer_id or seat.ready_timer_id == -1 then
        seat.ready_timer_id = 0
        seat.ready_timer_id = timer.settimer(seat.ready_to_time * 100,"doready",{seat_index = seat.index,rid = seat.rid})
    end
end

--
--- 准备
-- @param tableobj 牌桌对象
-- @param request 请求数据
-- @param seat 桌位对象
--
function TableLogic.gameready(tableobj, request, seat, roledata)
	local noticemsg = {
		rid = seat.rid,
		seat_index = seat.index,
		is_ready = false,
	}

	if seat.state == YYDBSeatState.SEAT_STATE_WAIT_START then 
		noticemsg.is_ready = true 
	end

    --已开局    
    if tableobj.is_had_start then
        if tableobj.is_ingame then  --游戏中
            seatlogic.onegamestart_initseat(seat)
            if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_OPENAWARD_COUNTDOWN then    --下注中，则通知玩家下注
                seat.state = YYDBSeatState.SEAT_STATE_WAIT_BET
                --通知玩家下注
                local noticemsg = {
                    wait_action_type = YYDBActionType.ACTION_TYPE_BET,
                    action_timeout_time = tableobj.action_timeout_time - 1,
                }
                TableLogic.sendmsg_to_tableplayer(seat.rid, "todoN", noticemsg)
            elseif tableobj.state <= YYDBTableState.TABLE_STATE_WAIT_PLAYER_BET then    --等待下注中
                seat.state = YYDBSeatState.SEAT_STATE_WAIT_BET
            else
                seat.state = YYDBSeatState.SEAT_STATE_INGAME_WATCH     --游戏中旁观
            end
        else
            seat.state = YYDBSeatState.SEAT_STATE_WAIT_START
        end
        return
    end

    --未开始第一局
	local isallready = false
	local playernum = 0
	for k, v in pairs(tableobj.seats) do
		if not seatlogic.is_empty(v) then
			if v.had_ready then
                playernum = playernum + 1
				isallready = true
                break
			end
		end
	end

	if isallready and playernum >= tableobj.min_player_num
    and tableobj.state == YYDBTableState.TABLE_STATE_WAIT_ALL_READY then		
        tableobj.state = YYDBTableState.TABLE_STATE_GAME_START
		gamelogic.run(tableobj.gameobj)
	end
end

--
-- doaction操作
--
function TableLogic.doaction(tableobj, rid, request, seat)
	local action_type = request.action_type or 0

    local call_func = nil
    if action_type == YYDBActionType.ACTION_TYPE_BET then                   --下注
        call_func = TableLogic.do_bet
    elseif action_type == YYDBActionType.ACTION_TYPE_CHANGE_SCORE then      --切换底注
        call_func = TableLogic.change_score
    else
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的操作类型"}
    end

    return call_func(tableobj, request, seat)
end

--
--获得玩家列表
--
function TableLogic.getplayerlist(tableobj, request, seat)
    local respmsg = { seat_roleinfos = {}, seat_gameinfos = {} }

    local playerlist = tableobj.player_list or {}
    local player_num = request.player_num or (#playerlist)

    --拷贝玩家信息
    local i = 0
    for _,seat_index in ipairs(playerlist) do
        local cur_seat = tableobj.seats[seat_index]
        if cur_seat and cur_seat.rid > 0 then
            i = i + 1
            if i > player_num then
                break
            end
            respmsg.seat_roleinfos[i] = TableLogic.copy_seat_roleinfo(cur_seat, true)
            --respmsg.seat_gameinfos[i] = TableLogic.copy_seat_gameinfo(cur_seat, true)
        end
    end
    
    return respmsg
end

--
--获得上庄列表
--
function TableLogic.getupbankerlist(tableobj, request, seat)
    local respmsg = { seat_roleinfos = {}, seat_gameinfos = {} }

    local max_len = #(tableobj.up_banker_list)
    local player_num = request.player_num or max_len
    if player_num > max_len then
        player_num = max_len
    end

    local up_banker_list = tableobj.up_banker_list or {}

    --拷贝玩家信息
    local i = 0
    for _,seat_index in ipairs(up_banker_list) do
        local cur_seat = tableobj.seats[seat_index]
        if cur_seat then
            i = i + 1
            if i > player_num then
                break
            end
            respmsg.seat_roleinfos[i] = TableLogic.copy_seat_roleinfo(cur_seat)
            respmsg.seat_gameinfos[i] = TableLogic.copy_seat_gameinfo(cur_seat)
            respmsg.seat_roleinfos[i].diamond = cur_seat.cur_upbanker_money
        end
    end
    
    return respmsg
end


function TableLogic.get_allbetplayer_num(tableobj)
    local betplayer_num = 0
    for betrid, betinfo in pairs(tableobj.open_award_random_codes_pool) do
        if betinfo ~= nil then betplayer_num = betplayer_num + 1 end
    end
    return betplayer_num
end

function TableLogic.check_bet_time_isover(tableobj)
    local is_bet_time_isover = true
    for betrid, betinfo in pairs(tableobj.open_award_random_codes_pool) do
        local seat = TableLogic.get_seat_by_rid(tableobj, betrid)
        if seat then
            if seat.cur_bet_cnt < tableobj.conf.each_bet_times then
                is_bet_time_isover = false
                break
            end
        end
    end
    return is_bet_time_isover
end

function TableLogic.get_player_betinfo(tableobj, rid)
    local betinfo = tableobj.open_award_random_codes_pool[rid]
    if not betinfo then 
        return nil
    else
        return betinfo
    end
end

--
--下注
--
function TableLogic.do_bet(tableobj, request, seat)
    local base_score_list = tableobj.conf.base_score_list
    local bet_item_id = request.bet_item_id or 0
    local bet_score = request.bet_score or 0

    if tableobj.state ~= YYDBTableState.TABLE_STATE_WAIT_OPENAWARD_COUNTDOWN then
        return {retcode = 0, retstr = ""}
    end

    --没有庄家
    -- if seat.index == tableobj.banker_seat_index then
    --     return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "庄家不能下注"}
    -- end

    --下注列表为空，则初始化
    if not seat.cur_bet_list then
        seat.cur_bet_list = TableLogic.gen_bet_list(tableobj)
        seat.cur_bet_cnt_list = seat.cur_bet_cnt_list or {}
        seat.cur_betcnt_inc_list = seat.cur_betcnt_inc_list or {}
    end

    --检测下注的合法性
    for _,base_score in pairs(base_score_list) do
        if base_score == bet_score then
            seat.cur_base_score = bet_score
            break
        end
    end

    if not seat or not seat.cur_bet_list[bet_item_id] 
        or bet_score ~= seat.cur_base_score then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数"}
    end

    --检测钱是否够
    local money = TableLogic.get_curmoney(seat)
    local total_bet = seat.cur_total_bet + bet_score
    local end_money = money - total_bet
    if end_money < 0 or money < 10 * 100 then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "您的余额不足"}
    end

    --检查是否达到总下注上限
    local total_bet = tableobj.cur_total_bet_num + bet_score
    local max_bet = tableobj.conf.total_bet_limit
    if total_bet > max_bet then
        return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "已达到下注上限"}
    elseif total_bet == max_bet then
        --达到最大下注，立即开奖
        ---skynet.send(tableobj.table_service, "lua", "timer", "spin_countdown", tableobj.timer_id, {}) 
    end

    --检查是否达到个人下注上限
    local player_cur_total_bet = seat.cur_total_bet + bet_score
    local player_max_bet = tableobj.conf.each_bet_limit
    if player_cur_total_bet > player_max_bet then
        return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "已达到下注上限"}
    end

    --检查是否达到个人下注次数限制
    if seat.is_robot == false then
        local player_cur_bet_cnt = seat.cur_bet_cnt + 1
        local player_max_bet_cnt = tableobj.conf.each_bet_times
        if player_cur_bet_cnt > player_max_bet_cnt then
            return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "已达到下注次数上限"}
        end
    else
        local player_cur_bet_cnt = seat.cur_bet_cnt + 1
        local player_max_bet_cnt = tableobj.conf.each_bet_times
        if player_cur_bet_cnt > player_max_bet_cnt then
            return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "已达到下注次数上限"}
        end
    end

    ----查看游戏玩法
    if tableobj.conf.game_type == YYDBGameType.GAME_TYPE_MANREN then
        ---判断下注金额
        local min_bet_num = tableobj.conf.min_bet_num
        if bet_score < min_bet_num then
            return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "下注金额太小"}
        end

        ----判断下注人数
        local max_betplayer_num = tableobj.conf.max_bet_player_num
        local get_all_betplayer_num = TableLogic.get_allbetplayer_num(tableobj)
        if get_all_betplayer_num >= max_betplayer_num then
            ----判断下注人中是否有自己,有自己就可以下注
            local player_bet = TableLogic.get_player_betinfo(tableobj, seat.rid)
            if player_bet == nil then
                return {retcode = EErrCode.ERR_DIAMOND_LIMIT, retstr = "下注人数超过上限"}
            end
        end
    end
    --统计总下注值
    tableobj.cur_total_bet_num = tableobj.cur_total_bet_num + bet_score

    --更新下注列表
    seat.cur_bet_cnt = seat.cur_bet_cnt + 1
    seat.cur_total_bet = (seat.cur_total_bet or 0) + bet_score
    seat.cur_bet_list[bet_item_id] = seat.cur_bet_list[bet_item_id] + bet_score
    tableobj.cur_total_bet_list[bet_item_id] = tableobj.cur_total_bet_list[bet_item_id] + bet_score
    if seat.is_robot then
        tableobj.cur_robot_total_bet_list[bet_item_id] = tableobj.cur_robot_total_bet_list[bet_item_id] + bet_score
    else
        tableobj.cur_player_total_bet_list[bet_item_id] = tableobj.cur_player_total_bet_list[bet_item_id] + bet_score
    end

    --记录下注次数变化
    seat.cur_bet_cnt_list[bet_item_id] = seat.cur_bet_cnt_list[bet_item_id] or {}
    seat.cur_betcnt_inc_list[bet_item_id] = seat.cur_betcnt_inc_list[bet_item_id] or {}
    tableobj.each_total_bet_cnt_list[bet_item_id] = tableobj.each_total_bet_cnt_list[bet_item_id] or {}
    tableobj.each_inc_bet_cnt_list[bet_item_id] = tableobj.each_inc_bet_cnt_list[bet_item_id] or {}

    local cur_inc_betcnt_list =  tableobj.each_inc_bet_cnt_list[bet_item_id]
    local cur_total_betcnt_list = tableobj.each_total_bet_cnt_list[bet_item_id]
    cur_total_betcnt_list[bet_score] = (cur_total_betcnt_list[bet_score] or 0) + 1
    cur_inc_betcnt_list[bet_score] = (cur_inc_betcnt_list[bet_score] or 0) + 1
    seat.cur_bet_cnt_list[bet_item_id][bet_score] = (seat.cur_bet_cnt_list[bet_item_id][bet_score] or 0) + 1
    seat.cur_betcnt_inc_list[bet_item_id][bet_score] = (seat.cur_betcnt_inc_list[bet_item_id][bet_score] or 0) + 1

    local get_codes_bets = {}

    ----初始化开奖码池
    if tableobj.open_award_random_codes_pool == nil then
        tableobj.open_award_random_codes_pool = {}
    end

    if tableobj.all_beted_players_codes[seat.rid] == nil then
        tableobj.all_beted_players_codes[seat.rid] = {}
    end

    if tableobj.open_award_random_codes_pool[seat.rid] == nil then
        tableobj.open_award_random_codes_pool[seat.rid] = {}
    end
    tableobj.open_award_random_codes_pool[seat.rid].get_code = seat.get_code
    tableobj.open_award_random_codes_pool[seat.rid].bet_num = (tableobj.open_award_random_codes_pool[seat.rid].bet_num or 0) + bet_score

    if seat.is_robot == true then
        table.insert(tableobj.all_beted_robot_codes, get_code)
    end
    
    --通知客户端
    local bet_list = { }
    for k,v in pairs(seat.cur_bet_list) do
        local item = {item_id = k, total_bet = v}
        if bet_item_id == k then
            item.cur_inc_betvalue = bet_score
        end
        table.insert(bet_list,item)
    end
    if tableobj.notice_betlist_timer == -1 or not tableobj.notice_betlist_timer then
        tableobj.notice_betlist_timer = 0   --settimer会被阻塞，防止设置多个timer
        tableobj.notice_betlist_timer = timer.settimer(100, "notice_totalbet_list")
    end

    --通知金钱改变
    if true then
        local noticemsg = {money_change_list = {}}
        local item = {
            rid = seat.rid,
            money_type = EMoneyType.DIAMOND, 
            change_value = -bet_score, 
            final_value = money - seat.cur_total_bet,
        }
        if TableLogic.is_cointable() then
            item.money_type = EMoneyType.COIN
        end
        table.insert(noticemsg.money_change_list,item)
        TableLogic.sendmsg_to_tableplayer(seat.rid,"moneychangeN",noticemsg)
    end

    ----判断游戏模式
    if tableobj.conf.game_type == YYDBGameType.GAME_TYPE_MANREN then
        ----判断下注人数
        local max_betplayer_num = tableobj.conf.max_bet_player_num
        local get_all_betplayer_num = TableLogic.get_allbetplayer_num(tableobj)
        if get_all_betplayer_num >= max_betplayer_num then
            -----直接开奖
            ---filelog.sys_error("------------人数达到，直接开奖-----------------")
            ---检查次数下完没有
            local is_over = TableLogic.check_bet_time_isover(tableobj)
            if is_over == true then
                skynet.send(tableobj.table_service, "lua", "timer", "spin_countdown", tableobj.timer_id, {})
            end
        end
    end
    return {action_type = request.action_type, cur_bet_list = bet_list, cur_total_bet_num = tableobj.cur_total_bet_num }
end

--
--更改底注,由小到大循环切换
--
function TableLogic.change_score(tableobj, request, seat)
    local base_score_list = tableobj.conf.base_score_list
    local cur_score = seat.cur_base_score
    local new_score = nil

    --指定切换到某底注
    if request.base_score_index then
        new_score = base_score_list[request.base_score_index] or cur_score
    else
        for i,v in ipairs(base_score_list) do
            if v == cur_score then
                new_score = base_score_list[i+1]
                break
            end
        end
    end

    --没找到，则返回第一个可选底注
    if not new_score then
        new_score = base_score_list[1]
    end
    seat.cur_base_score = new_score

    return {action_type = request.action_type, cur_base_score = new_score}
end

--
--上庄
--
function TableLogic.up_banker(tableobj, request, seat)
    local cur_total_bet = seat.cur_total_bet or 0
    local up_banker_money = tableobj.conf.up_banker_money or 0
    local cur_upbanker_money = request.cur_upbanker_money or 0
    local curmoney = TableLogic.get_curmoney(seat) - cur_total_bet

    --如果是机器人，随机上庄金额
    if seat.is_robot and curmoney > up_banker_money then
        local min = math.floor(up_banker_money / 10000)
        local max = math.floor(curmoney / 10000)
        if min > max then min = max end
        if max > 120 then max = 120 end
        if max > 50 and min < 40 then min = base.get_random(min, 50) end
        cur_upbanker_money = base.get_random(min, max) * 10000
    end

    --检查金币是否足够
    if cur_upbanker_money > curmoney or cur_upbanker_money < up_banker_money then
        return {retcode = EErrCode.ERR_NOT_ENOUGH_DIAMOND, retstr = "余额不足，不能上庄"}
    end

    --已经上庄
    if tableobj.banker_seat_index == seat.index then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "已经上庄"}
    end

    --检查是否已在上庄列表
    for k,v in pairs(tableobj.up_banker_list) do
        if v == seat.index then
            return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "已经在上庄列表"}
        end
    end

    --加入等待上庄列表
    local insert_pos = #(tableobj.up_banker_list) + 1
    for i,v in ipairs(tableobj.up_banker_list) do
        local tmpseat = tableobj.seats[v]
        if tmpseat and tmpseat.cur_upbanker_money < cur_upbanker_money then
            insert_pos = i
            break
        end
    end
    table.insert(tableobj.up_banker_list,insert_pos,seat.index)

    --保存当前上庄金额
    seat.cur_upbanker_money = cur_upbanker_money
    seat.cur_upbanker_time = timetool.get_time()

    --返回
	local up_banker_list = tabletool.deepcopy(tableobj.up_banker_list)
    return {action_type = request.action_type, up_banker_list = up_banker_list}
end

--
--下庄
--
function TableLogic.down_banker(tableobj, request, seat)
    local cur_banker_index = tableobj.banker_seat_index
    if seat.index == cur_banker_index then
        tableobj.is_down_banker = true
    else
        --在上庄列表，则将其清除
        for k,v in pairs(tableobj.up_banker_list) do
            if v == seat.index then
                table.remove(tableobj.up_banker_list,k)
                break
            end
        end

        --清除当前上庄金额
        seat.cur_upbanker_money = 0
        seat.cur_upbanker_time = nil
    end

    --返回
	local up_banker_list = tabletool.deepcopy(tableobj.up_banker_list)
    return {action_type = request.action_type, up_banker_list = up_banker_list}
end


function TableLogic.getmycodes(tableobj, rid, request, seat)
    local all_my_codes = {}
    for key, code in pairs(seat.cur_get_codes) do
        table.insert(all_my_codes, code)
    end
    return {get_codes_list = all_my_codes}
end

--
--主动离桌
--
function TableLogic.leavetable(tableobj, request, rid, curmoney)
    local leavetablemsg = {
        rid = rid,
		table_index = tableobj.index,
	}

    if tableobj.waits[rid] ~= nil then
		TableLogic.sendmsg_to_alltableplayer(tableobj, "leavetableN", leavetablemsg)
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1
        --通知router,删除rid-table的映射,并通知gate
        if not tableobj.waits[rid].is_robot then
            skynet.send(".router","lua","leave_table",nil,rid,tableobj.index,curmoney)
        else
            skynet.send(".robotmgr", "lua", "delete_robot", rid)
        end
	end
    tableobj.waits[rid] = nil

    --桌子正在删除直接返回
	if tableobj.isdeleting then
		return
	end

    --重置桌子数据
    if tableobj.is_had_start then
        gamelogic.reset_tabledata(tableobj.gameobj)
    end

	if tableobj.is_had_start then
		if tableobj.sitdown_player_num <= 0 then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	else
		if tableobj.sitdown_player_num <= 0 and tableobj.cur_watch_playernum <= 0 then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	end
end

--
--- 被动离桌
-- @param tableobj
-- @param rid
-- @param is_leave
--被动离开桌子，使用该接口时玩家必须是在旁观中
--记住使用者如果循环遍历旁观队列一定要使用原队列的copy队列
--
function TableLogic.passive_leavetable(tableobj, rid, curmoney, is_leave, reason)
	local leavetablemsg = {
        rid = rid,
		table_index = tableobj.index,
        reason = reason,
	}

	if tableobj.waits[rid] ~= nil then
		TableLogic.sendmsg_to_alltableplayer(tableobj, "leavetableN", leavetablemsg)
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum - 1
        --通知router,删除rid-table的映射,并通知gate
        if not is_leave and not tableobj.waits[rid].is_robot then
            skynet.send(".router","lua","leave_table",nil,rid,tableobj.index,curmoney)
        end
        if tableobj.waits[rid].is_robot then
            skynet.send(".robotmgr", "lua", "delete_robot", rid)
        end
	end
	tableobj.waits[rid] = nil

    --桌子正在删除直接返回
	if tableobj.isdeleting then
		return
	end

    --重置桌子数据
    if tableobj.is_had_start then
        gamelogic.reset_tabledata(tableobj.gameobj)
    end

    --游戏已经开始
	if tableobj.is_had_start then
		if tableobj.sitdown_player_num <= 0 then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
            if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	else    --未开始，直接删除
		if tableobj.sitdown_player_num <= 0 and tableobj.cur_watch_playernum <= 0 then
			if tableobj.delete_table_timer_id > 0 then
				timer.cleartimer(tableobj.delete_table_timer_id)
				tableobj.delete_table_timer_id = -1
			end
			if tableobj.delete_table_timer_id == -1 then
                tableobj.delete_table_timer_id = 0
                tableobj.delete_table_timer_id = timer.settimer(100, "delete_table")
            end
		end
	end
end

--
-- 被动站起
--
function TableLogic.passive_standuptable(tableobj, request, seat, reason, is_sendto_client)
    if seat.state == YYDBSeatState.SEAT_STATE_NO_PLAYER then
        return
    end

	tableobj.sitdown_player_num = tableobj.sitdown_player_num - 1 
	local standuptablemsg = {
		rid = seat.rid,
		seat_index = seat.index,
		table_index = tableobj.index,
        reason = reason,
	}

    --通知客户端
	TableLogic.sendmsg_to_alltableplayer(tableobj, "standuptableN", standuptablemsg)
    seat.state = YYDBSeatState.SEAT_STATE_NO_PLAYER

    --保存进旁观列表
	if tableobj.waits[seat.rid] == nil then
		local waitinfo = {
			playerinfo = {},
		}
		tableobj.waits[seat.rid] = waitinfo
		waitinfo.rid = seat.rid
        waitinfo.playerinfo.coin = seat.playerinfo.coin
        waitinfo.playerinfo.diamond = seat.playerinfo.diamond
        waitinfo.is_robot = seat.is_robot
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1
	end

	---
	--初始化座位数据
	gamelogic.standup_clear_seat(tableobj.gameobj, seat)
end

--
-- 主动站起
--
function TableLogic.standuptable(tableobj, request, seat)
    if seat.state == YYDBSeatState.SEAT_STATE_NO_PLAYER then
        return
    end

	tableobj.sitdown_player_num = tableobj.sitdown_player_num - 1
	local noticemsg = {
		rid = seat.rid, 
		seat_index = seat.index,
		table_index = tableobj.index,
		reason = EStandupReason.STANDUP_REASON_ONSTANDUP,
	}

	if tableobj.state == YYDBTableState.TABLE_STATE_UNKNOW then
		TableLogic.sendmsg_to_tableplayer(seat.rid, "standuptableN", noticemsg)
	else
		TableLogic.sendmsg_to_alltableplayer(tableobj, "standuptableN", noticemsg)
	end

    seat.state = YYDBSeatState.SEAT_STATE_NO_PLAYER
	if tableobj.waits[seat.rid] == nil then
		local waitinfo = {
			playerinfo = {},
		}
		tableobj.waits[seat.rid] = waitinfo
		waitinfo.rid = seat.rid
        waitinfo.playerinfo.coin = seat.playerinfo.coin
        waitinfo.playerinfo.diamond = seat.playerinfo.diamond
        waitinfo.is_robot = seat.is_robot
		tableobj.cur_watch_playernum = tableobj.cur_watch_playernum + 1
	end

	--初始化座位数据
	gamelogic.standup_clear_seat(tableobj.gameobj, seat)
end

--
--  所有玩家离桌
--
function TableLogic.leavetableallplayer(tableobj,reason)
    if type(tableobj.seats) ~= "table" then
        return
    end

	for _, seat in pairs(tableobj.seats) do
		if not seatlogic.is_empty(seat) then
            local rid,money = seat.rid,TableLogic.get_curmoney(seat)
			TableLogic.passive_standuptable(tableobj, nil, seat, reason)
			TableLogic.passive_leavetable(tableobj,rid,money)
		end
	end
end

--- 断线重连处理函数
-- @param tableobj
-- @param request
-- @param seat
--
function TableLogic.reentertable(tableobj, request, seat)
	local noticemsg
	local player_action
	local tmpseat
    local cur_player_action

    --更改断线状态
    if seat.is_disconnected then
	    seat.is_disconnected = false
    end

    --清除断线计时器
    if seat.disconnect_timer_id > 0 then
        timer.cleartimer(seat.disconnect_timer_id)
        seat.disconnect_timer_id = -1
    end

    --更改离开状态，通知所有玩家
	if seat.is_leave then
		seat.is_leave = false
		local noticemsg = {
			rid = seat.rid,
			seat_index = seat.index,	
		}
		TableLogic.sendmsg_to_tableplayer(seat.rid,"reentertableN", noticemsg)
	end

    --等待准备,则发送准备
	if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_ALL_READY 
	and seat.state == YYDBSeatState.SEAT_STATE_WAIT_READY then
        --TableLogic.sendmsg_to_tableplayer(seat.rid, "doreadyN", {action_timeout_time = seat.ready_timeout_time})
        return
	end

    -- --摇骰子中，通知摇骰子
    -- if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_PLAYER_BET then
    --     local banker_seat = tableobj.seats[tableobj.banker_seat_index] or tableobj.sys_banker_info
	   --  noticemsg = {
		  --   rid = banker_seat.rid,
		  --   seat_index = banker_seat.index,
		  --   dice_one = tableobj.dice_one,		
		  --   dice_two = tableobj.dice_two,
	   --  }
    --     TableLogic.sendmsg_to_tableplayer(seat.rid, "shakediceN", noticemsg)
    --     return
    -- end

    --下注中，则通知下注
    if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_OPENAWARD_COUNTDOWN then
        noticemsg = {
            wait_action_type = YYDBActionType.ACTION_TYPE_BET,
            action_timeout_time = tableobj.action_timeout_time - 1,
        }
        TableLogic.sendmsg_to_tableplayer(seat.rid, "todoN", noticemsg)
        return
    end

    --开奖中，则通知开奖
    if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_HANDLE_OPENAWARD_RESULT then
        local rand_result = tableobj.rand_result_list or {}
        noticemsg = {
            player_cards = {},
            banker_cards = {},
            opencard_result = tabletool.deepcopy(tableobj.opencard_result),
        }
        for i = 1,4 do
            local all_result = rand_result.all_results[i] or {}
            local item = {
                cards = tabletool.deepcopy(rand_result.all_cards[i]), 
                cards_type = all_result.cards_type or 0, 
                points = all_result.points or 0,
            }
            if i == 1 then
                noticemsg.banker_cards = item
            else
                table.insert(noticemsg.player_cards,item)
            end
        end
        TableLogic.sendmsg_to_tableplayer(seat.rid, "opencardN", noticemsg)
        return
    end
end

--------------------------------------------
--send方法
--

--
-- 通知桌上所有玩家
--
function TableLogic.sendmsg_to_alltableplayer( tableobj, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local seats = tableobj.seats
    for i,seat in pairs(seats) do
       if not seatlogic.is_empty(seat) 
       and not seat.is_disconnected 
       and not seat.is_robot then
            table.insert(rids,seat.rid)
       end 
    end

    if tableobj.waits ~= nil then
        for i,wait in pairs(tableobj.waits) do
            if not wait.is_robot then
                table.insert(rids,wait.rid)
            end
        end
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知桌上除某玩家之外的所有玩家
-- rid 排除的玩家
--
function TableLogic.sendmsg_to_otheralltableplayer( tableobj,rid, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local seats = tableobj.seats
    for i,seat in pairs(seats) do
       if not seatlogic.is_empty(seat) and seat.rid ~= rid and 
       not seat.is_disconnected and not seat.is_robot then
            table.insert(rids,seat.rid)
       end 
    end

     if tableobj.waits ~= nil then
        for i,wait in pairs(tableobj.waits) do
            if wait.rid ~= rid and not wait.is_robot then
                table.insert(rids,wait.rid)
            end
        end
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知桌上某个玩家
--
function TableLogic.sendmsg_to_tableplayer( rid, msgname, message)
    local seat = TableLogic.get_seat_by_rid(service.table_data,rid) or {}
    if seat.is_disconnected or seat.is_robot then
        return
    end

    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    table.insert(rids,rid) 
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 通知所有旁观列表玩家
--

function TableLogic.sendmsg_to_allwaitplayer(tableobj, msgname, message)
    local retcode,retstr,msgbody
    if message and message.retcode  then
		retcode = tonumber(message.retcode)
		retstr = message.retstr or ""
		msgbody = message.msgbody or { }
    else
        msgbody = message
	end

    local rids = { }
    local waits = tableobj.waits
    for i,wait in pairs(waits) do
       if wait.rid and not wait.is_robot then
            table.insert(rids,wait.rid)
       end 
    end
    
    service:send_notice_to_players(rids, msgname, msgbody, retcode, retstr)
end

--
-- 更新桌子心跳时间
--
function TableLogic.update_table_heart_time(tableobj)
    tableobj.last_heart_time = timetool.get_time()
end

--
-- 设置所有座位状态
--
function TableLogic.setallseatstate(tableobj, state)
	for k,value in pairs(tableobj.seats) do
		value.state = state
	end
end


--------------------------------------------
--金钱相关

--
-- 结算后钻石信息，每局结算都要通知gate
-- rid_value {beginvalue,value,endvalue,rolename}
--
function TableLogic.game_balance_diamond(rid_values)
    local comment = TableLogic.create_comment()
    local status,result = skynet.pcall(cluster.call,"gatenode", ".router", "brgame_balance_diamond", rid_values, comment)
    if not status then
        filelog.sys_error("game_balance_diamond call failed!")
        return false
    else
        --记录流水日志
        local total_bet = 0
        local total_water = 0
        local sys_change = 0
        local total_change = 0
        for rid,item in pairs(rid_values) do
            total_water = total_water + math.abs(item.real_change or 0)
            total_bet = total_bet + (item.total_bet or 0)
            sys_change = sys_change + item.real_change
            total_change = total_change + item.value

            --记录下注值
            local bet_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.DOBET, rid, item.level, 
            item.total_bet, 0, 0, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            skynet.send(".diamondlog", "lua", "write", bet_logstr)
            --记录流水变化值
            local chg_logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, rid, item.level, item.real_change, 
            item.beginvalue,item.endvalue, 0, 0, 0, comment.table_uuid, comment.start_time, comment.table_tradeid)
            if item.real_change ~= 0 then
                skynet.send(".diamondlog", "lua", "write_file_redis", chg_logstr, rid)
            else
                skynet.send(".diamondlog", "lua", "write", chg_logstr)
            end
        end
        --记录系统的流水变化
        local logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.FUWUFEI, 0, 0, -sys_change, 0, 0, 0, 0, 0,
        comment.table_uuid, comment.start_time, comment.table_tradeid)
        skynet.send(".diamondlog", "lua", "write", logstr)

        --更新收益值,库存值，扣除抽水
        local tableobj = service.table_data
        local gamename =  TableLogic.get_gamename(tableobj)
        skynet.call(".slotmgr", "lua", "handle_balance_result", gamename, total_change, total_water, total_bet, comment)
    end
    return result,comment
end

--
--  改变金钱
--
function TableLogic.change_money(rid, itemvalues)
    local comment = TableLogic.create_comment()
    local status,result = skynet.pcall(cluster.call,"gatenode", ".router", "change_money", rid, itemvalues, comment)
    if not status then
        filelog.sys_error("change_money call failed!")
        return false
    end
    return result,comment
end

--------------------------------------------
--get方法
--

--
--根据rid获得座位对象
--
function TableLogic.get_seat_by_rid(tableobj, rid)
	if tableobj.seats == nil then
		return nil
	end

	for index, seat in pairs(tableobj.seats) do
		if rid == seat.rid then
			return seat
		end
	end
	return nil
end

--- 根据玩家的rid查找玩家是否在旁观队列
-- @param tableobj 牌桌对象
-- @param rid  玩家rid
function TableLogic.get_waitplayer_by_rid(tableobj, rid)
	for index, waitplayer in pairs(tableobj.waits) do
		if rid == waitplayer.rid then
			return waitplayer
		end
	end
	return nil
end

--
--- 根据指定桌位号获得一张空座位
-- @param tableobj 牌桌对象
-- @param index 座位号
function TableLogic.get_emptyseat_by_index(tableobj, index)
	if index == nil or index <= 0 or index > tableobj.conf.max_player_num then
		for index, seat in pairs(tableobj.seats) do
			if seatlogic.is_empty(seat) then
				return seat
			end
		end
	else
		local seat = tableobj.seats[index]
		if seatlogic.is_empty(seat) then
			return seat
		end
	end
	return nil
end

--
-- 获得桌子索引号
--
function TableLogic.get_table_index(tableobj)
	return tableobj.table_index
end

--
-- 获得坐下玩家数
--
function TableLogic.get_sitdown_player_num(tableobj)
	return tableobj.sitdown_player_num
end

--
-- 获得游戏中玩家数
--
function TableLogic.get_ingame_playernum(tableobj)
	local playernum = 0	
	for _, seat in pairs(tableobj.seats) do
		if gamelogic.is_ingame(tableobj.gameobj, seat) then
			playernum = playernum + 1
		end
	end
	return playernum
end

--------------------------------------------
--is方法
--

--- 判断当前桌子是否坐满
-- @param tableobj  牌桌对象
--
function TableLogic.is_full(tableobj)
	return (tableobj.sitdown_player_num >= tableobj.conf.max_player_num)
end

---判断当前是否能够开始游戏
-- @param tableobj	牌桌对象
--
function TableLogic.is_canstartgame(tableobj)
	return (tableobj.sitdown_player_num >= tableobj.min_player_num)
end

--- 判断游戏是否结束
-- @param tableobj 牌桌对象
--
function TableLogic.is_gameend(tableobj)
	if tableobj.state == YYDBTableState.TABLE_STATE_GAME_END
	or tableobj.state == YYDBTableState.TABLE_STATE_WAIT_PLAYER_SITDOWN
	or tableobj.state == YYDBTableState.TABLE_STATE_UNKNOW then
		return true
	end

	return false
end

--- 判断当前局是否已经结束游戏
-- @param tableobj 牌桌对象
--
function TableLogic.is_onegameend(tableobj)
	if tableobj.state == YYDBTableState.TABLE_STATE_ONE_GAME_REAL_END
	or tableobj.state == YYDBTableState.TABLE_STATE_WAIT_ALL_READY 
    or tableobj.state == YYDBTableState.TABLE_STATE_WAIT_ONE_GAME_START then
		return true
	end

	if not tableobj.is_ingame then
		return true
	end

	return TableLogic.is_gameend(tableobj)
end

--------------------------------------------
--copy方法
--

--
-- 这是要按照proto来组织，然后返回给客户端
--
function TableLogic.copy_table_gameinfo(self_index, is_no_rankdata)
    --[[
        //牌局信息的汇总大集合，也是最重要的数据结构，
        message table_gameinfo{
            optional table_baseinfo table_baseinfo  = 1;
            optional table_conf     table_conf      = 2;
            repeated seat_roleinfo  seat_roleinfos  = 3; //两者按照座位号对应
            repeated seat_gameinfo  seat_gameinfos  = 4; //两者按照座位号对应
        }
    ]]

    local table_data = service.table_data
	local gameinfo = {}
	
    --[[

    --]]
    gameinfo.table_conf = {
        table_type          = table_data.conf.table_type, --       //类型 1：金币
        max_player_num      = table_data.conf.max_player_num,       --//桌子支持最大玩家数（旁观的不算）默认12人
        is_public           = table_data.conf.is_public,       --//是否公开，列表里可以看见（1:公开，0：私密好友）
        base_score_list     = table_data.conf.base_score_list,  --       //底注列表，形如：{10,100,500,5000}
        min_carry_amount    = table_data.conf.min_carry_amount, --      //最小携带量
        max_carry_amount    = table_data.conf.max_carry_amount, --       //最大携带量
        odds_list           = table_data.conf.odds_list, --       //赔率列表
        each_bet_limit      = table_data.conf.each_bet_limit, --       //每门下注上限
        total_bet_limit     = table_data.conf.total_bet_limit, --       //总下注上限
        each_bet_times      = table_data.conf.each_bet_times, --      //每人限制下注次数
        code_price          = table_data.conf.code_price, 
        bet_btn_list        = table_data.conf.bet_btn_list, --      //下注按钮列表
    }
	gameinfo.seat_roleinfos = {}
	gameinfo.seat_gameinfos = {}
    gameinfo.table_baseinfo = {}
    --[[
    //桌子的基本相关信息
    message table_baseinfo{
        optional int32  table_type                  = 1;            //这里和 table_conf 里面重合，是为了使用方便
        optional int32  game_type                   = 2;            //游戏玩法(1 不定人数 2 定人数)
        optional string uuid                        = 3;            //桌子的唯一id，nodename_timenow_code，查看大战绩时也可以使用
        optional int32  index                       = 4;            //桌子在table中的序列号 ,这里用的id，就是index
        optional int32  code                        = 5;            //随机桌号,客户端也显示成房间号
        optional int32  state                       = 6;            //table 状态（准备， 玩牌）
        optional int32  create_rid                  = 7;            //创建者rid
        optional string create_rolename             = 8;            //创建者姓名
        optional int32  create_time                 = 9;            //桌子的创建时间
        optional int32  sitdown_player_num          = 10;           //当前坐在位置上人数
        optional string cur_qishu                   = 11;           //当期期数
        optional int32  cur_bet_player_num          = 12;           //当前下注玩家数
        optional int32  cur_total_bet_num           = 13;           //当前总下注值
        repeated betitem cur_total_bet_list         = 14;           //当前总下注列表
        optional string openaward_codes             = 15;           //中奖的随机码
        optional int32  getaward_rid                = 16;           //获奖玩家rid
        optional string getaward_rolename           = 17;           //获奖玩家名字
        optional int32  getaward_num                = 18;           //实际得到的金额(扣除手续费之后)
        optional int32  allawardpool_num            = 19;           //奖池金额
        optional string logo                        = 20;           //获奖玩家头像
        optional string bet_rank_data               = 21;           //前几名下注情况
        repeated wangqi wangqi_lists                = 22;           //往期金奖得主(6组) 
    }
    --]]
    gameinfo.table_baseinfo.table_type              = table_data.conf.table_type
    gameinfo.table_baseinfo.game_type               = table_data.conf.game_type
	gameinfo.table_baseinfo.uuid                    = table_data.uuid 
	gameinfo.table_baseinfo.index                   = table_data.index 
	gameinfo.table_baseinfo.code                    = table_data.code 
	gameinfo.table_baseinfo.state                   = table_data.state 
	gameinfo.table_baseinfo.create_rid              = table_data.create_rid 
	gameinfo.table_baseinfo.create_rolename         = table_data.create_rolename 
	gameinfo.table_baseinfo.create_time             = table_data.create_time 
	gameinfo.table_baseinfo.sitdown_player_num      = table_data.sitdown_player_num
    gameinfo.table_baseinfo.cur_qishu               = tostring(table_data.today_already_times) or 0 
    gameinfo.table_baseinfo.cur_bet_player_num      = table_data.cur_bet_player_num
    gameinfo.table_baseinfo.cur_total_bet_num       = table_data.cur_total_bet_num
    gameinfo.table_baseinfo.openaward_codes = ""           ---//中奖的随机码
    gameinfo.table_baseinfo.getaward_rid    = 0            ---//获奖玩家rid
    gameinfo.table_baseinfo.getaward_rolename  = ""     ---//获奖玩家名字
    gameinfo.table_baseinfo.getaward_num       = 0           ---//实际得到的金额(扣除手续费之后)
    gameinfo.table_baseinfo.allawardpool_num   = 20         ---//奖池金额
    gameinfo.table_baseinfo.logo               = ""           ---//获奖玩家头像
    if is_no_rankdata == true then
        gameinfo.table_baseinfo.bet_rank_data = json.encode({})
    else
        local send_player_bet_rank_data = {}
        for index, rank_data in ipairs(table_data.player_bet_rank_data) do
            if index <= 10 then
                table.insert(send_player_bet_rank_data, rank_data)
            end
        end
        gameinfo.table_baseinfo.bet_rank_data  = json.encode(send_player_bet_rank_data)
    end
    gameinfo.table_baseinfo.wangqi_lists = {}

    local from_record_list = tabletool.deepcopy(table_data.history_record_lists)

    table.sort(from_record_list, function(first, second) 
        if first.open_award_time > second.open_award_time then
            return true
        else
            return false
        end
    end)
    
    for key, record in ipairs(from_record_list) do
        --[[
        //往期金奖得主
        message wangqi {
            optional string qishu       = 1;    // 期数
            optional string award_code  = 2;    // 获奖幸运码
            optional int32  award_num   = 3;    // 奖金
            optional string rolename    = 4;    // 获奖玩家名字
        }
        --]]
        local base_records = {
            qishu = tostring(record.today_times),
            award_code = record.getaward_code,
            award_num = record.award_num,
            rolename = record.rolename,
        }
        if #gameinfo.table_baseinfo.wangqi_lists < 10 then
            table.insert(gameinfo.table_baseinfo.wangqi_lists, base_records)
        end
    end
    table.sort(gameinfo.table_baseinfo.wangqi_lists, function(first, second)
            if tonumber(first.qishu) < tonumber(second.qishu) then
                return true
            else
                return false
            end
        end)

    if table_data.cur_total_bet_list then
        local total_bet_list = { }
        for k,v in pairs(table_data.cur_total_bet_list) do
            local total_list = table_data.each_total_bet_cnt_list[k]
            table.insert(total_bet_list,{item_id = k, total_bet = v, each_total_bet_cnt = json.encode(total_list)})
        end
        gameinfo.table_baseinfo.cur_total_bet_list = total_bet_list
    end
    --拷贝座位信息
    local all_seats_info = TableLogic.copy_all_seats_info(self_index)
    gameinfo.seat_roleinfos = all_seats_info.seat_roleinfos
    gameinfo.seat_gameinfos = all_seats_info.seat_gameinfos
	return gameinfo
end

--
--拷贝所有座位信息
--
function TableLogic.copy_all_seats_info(self_index)
    local tableobj = service.table_data
    local all_seats_info = {seat_roleinfos = {}, seat_gameinfos = {}}

    --首先拷贝特权位
    local idx = 1
    local self_inspseat = false
    local special_seats = {}
    local spnum = tableobj.special_seats_num
    for _,seat_index in ipairs(special_seats) do
        local spseat = tableobj.seats[seat_index]
        if spseat then --and spseat.index ~= self_index then
            if spseat.index == self_index then
                self_inspseat = true
            end
            all_seats_info.seat_roleinfos[idx] = TableLogic.copy_seat_roleinfo(spseat)
		    all_seats_info.seat_gameinfos[idx] = TableLogic.copy_seat_gameinfo(spseat)
            all_seats_info.seat_gameinfos[idx].index = idx
            idx = idx + 1
            if idx > spnum then
                break
            end
        end
    end

  --   --拷贝庄家的信息
  --   if tableobj.banker_seat_index then
  --       local banker_seat = tableobj.seats[tableobj.banker_seat_index] or tableobj.sys_banker_info
  --       all_seats_info.seat_roleinfos[idx] = TableLogic.copy_seat_roleinfo(banker_seat)
		-- all_seats_info.seat_gameinfos[idx] = TableLogic.copy_seat_gameinfo(banker_seat)
  --       all_seats_info.seat_gameinfos[idx].index = idx
  --       idx = idx + 1
  --   end

    --拷贝自己的信息
    if not self_inspseat and self_index and tableobj.banker_seat_index ~= self_index and tableobj.seats[self_index] then
        local self_seat = tableobj.seats[self_index]
        all_seats_info.seat_roleinfos[idx] = TableLogic.copy_seat_roleinfo(self_seat)
		all_seats_info.seat_gameinfos[idx] = TableLogic.copy_seat_gameinfo(self_seat)
        all_seats_info.seat_gameinfos[idx].index = idx
    end

    return all_seats_info
end

--
--拷贝座位游戏信息
--
function TableLogic.copy_seat_gameinfo(seat, is_limit)
    --[[
    //座位上和游戏相关的信息，随着游戏的进行，会进行变化的，包括钻石
    message seat_gameinfo {
        optional int32 rid              = 1;
        optional int32 index            = 2;                //位置座位编号
        optional int32 state            = 3;                //等待准备，等待开局，游戏中
        optional int32 offline          = 4;                //1断线，0在线
        optional int32 is_banker        = 5;                // 是否是庄家
        optional int32 cur_money        = 6;                //当前金钱数
        optional int32 cur_total_bet    = 7;                //当前总下注金额 = 每门下注金额之和
        optional int32 cur_base_score   = 8;                //当前底注
        optional string mycode          = 9;                //当局我的幸运码
        repeated betitem cur_bet_list   = 10;               //当前下注列表
        optional int32 last_win_score   = 11;               //上局输赢数，nil表示输赢为0
        optional int32 late_total_bet   = 12;               //近20局总下注
        optional int32 win_num          = 13;               //近20局获胜局数
    }
    ]]
    local seat_gameinfo ={}
    seat_gameinfo.rid		= seat.rid
    seat_gameinfo.index		= seat.index
    seat_gameinfo.cur_money	= TableLogic.get_curmoney(seat)
    if not is_limit then
        seat_gameinfo.state		= seat.state
        seat_gameinfo.win_num =  seat.win_num
        seat_gameinfo.late_total_bet = seat.late_total_bet
        seat_gameinfo.offline	= (seat.is_disconnected and 1) or 0
        seat_gameinfo.is_banker = (seat.is_banker and 1) or 0
        seat_gameinfo.cur_money = seat.playerinfo.diamond
        seat_gameinfo.cur_total_bet = seat.cur_total_bet
        seat_gameinfo.cur_base_score	= seat.cur_base_score
        seat_gameinfo.last_win_score = seat.last_win_score
        seat_gameinfo.mycode        = seat.get_code
        if seat.cur_bet_list then
            local cur_bet_list = { }
            for k,v in pairs(seat.cur_bet_list) do
                table.insert(cur_bet_list,{item_id = k, total_bet = v})
            end
            seat_gameinfo.cur_bet_list = cur_bet_list
        end
    end
    return seat_gameinfo
end

--
--拷贝座位角色信息
--
function TableLogic.copy_seat_roleinfo(seat, is_limit)
    local seat_roleinfo = {}
    seat_roleinfo.rid = seat.rid
    seat_roleinfo.rolename = seat.playerinfo.rolename
    seat_roleinfo.logo = seat.playerinfo.logo
    seat_roleinfo.diamond = seat.playerinfo.diamond
    if not is_limit then
        seat_roleinfo.sex = seat.playerinfo.sex
        seat_roleinfo.coin = seat.playerinfo.coin
        seat_roleinfo.intro = seat.playerinfo.intro
        seat_roleinfo.ip_addr = seat.playerinfo.ip_addr
        seat_roleinfo.gps_addr = seat.playerinfo.gps_addr
        seat_roleinfo.upvoted_num = seat.playerinfo.upvoted_num
        seat_roleinfo.downvoted_num = seat.playerinfo.downvoted_num
        seat_roleinfo.logoframe = seat.playerinfo.logoframe
    end
    return seat_roleinfo
end

------------------------------------------------
--其他

--清空桌子对象数据
--
function TableLogic.clear(tableobj)
	if tableobj.timer_id > 0 then
		timer.cleartimer(tableobj.timer_id)
		tableobj.timer_id = -1
	end

	if tableobj.delete_table_timer_id > 0 then
		timer.cleartimer(tableobj.delete_table_timer_id)
		tableobj.delete_table_timer_id = -1
	end

	for k,v in pairs(tableobj) do
		tableobj[k] = nil
	end
end

--
--创建comment
--
function  TableLogic.create_comment()
    local tableobj = service.table_data
    local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
    local start_time = tableobj.one_start_time or 0
   
    return {table_uuid = tableobj.uuid ,table_tradeid = tradeid,start_time = start_time,jackpot_id = tableobj.cur_jackpot_id}
end

--
--断开连接(断线）
--
function TableLogic.disconnect(tableobj, request, seat)
	seat.is_disconnected = true
	seat.is_leave = true
	local noticemsg = {
		rid = seat.rid,
		seat_index = seat.index,	
	}

	TableLogic.sendmsg_to_tableplayer(seat.rid,"disconnectN", noticemsg)

    --断线60s后，将其踢出
    if seat.disconnect_timer_id == -1 then
        seat.disconnect_timer_id = 0
        seat.disconnect_timer_id = timer.settimer(60 * 100, "disconnect_outtime", {index = seat.index})
    end

    if tableobj.state == YYDBTableState.TABLE_STATE_WAIT_ALL_READY 
        and seat.state == YYDBSeatState.SEAT_STATE_WAIT_READY then
        local rid,money = seat.rid,TableLogic.get_curmoney(seat)
        TableLogic.passive_standuptable(tableobj, {}, seat, EStandupReason.STANDUP_REASON_DISCONNECTED)	
        TableLogic.passive_leavetable(tableobj,rid,money)
    end
end

--
--生成一个下注列表
--
function TableLogic.gen_bet_list(tableobj)
    local bet_btn_list = tableobj.conf.bet_btn_list
    local new_bet_list = {}
    for _,id in pairs(bet_btn_list) do
        new_bet_list[id] = 0
    end
    
    return new_bet_list
end

------------------------------------------------------------------------
------------------------------------------------------------------------

--- 保存牌桌每局记录
-- @param game_records 游戏记录
--
function TableLogic.save_table_records(game_records)
    if not game_records.user_count or game_records.user_count <= 0 then
        return
    end

    local tablerecords = {}

    tablerecords.user_count = game_records.user_count                       --游戏总人数
    tablerecords.sys_diamond_start = game_records.sys_diamond_start         --系统开始元宝
    tablerecords.sys_diamond_end = game_records.sys_diamond_end             --系统结束元宝
    tablerecords.today_already_times = game_records.today_already_times     
    tablerecords.begin_time = game_records.one_start_time                   --本局开始时间
    tablerecords.end_time = game_records.one_end_time                       --本局结束时间
    tablerecords.game_type = skynet.getenv("nodename")                      --游戏类型
    tablerecords.room_num = game_records.table_code                         --房间号
    tablerecords.game_info = game_records.players_balance_list              --玩家结算信息
    ---tablerecords.opencard_result = game_records.opencard_result             --开牌结果
    tablerecords.open_award_result = game_records.open_award_result
    tablerecords.player_codes_info = game_records.player_codes_info
    tablerecords = json.encode(tablerecords)

    --调用日志服务写到文件
	skynet.send(".tablerecordlog", "lua", "write",game_records.cur_record_id,tablerecords)
end

--- 保存牌桌最终记录(桌子被删除时）
-- @param tableobj 桌子对象
--
function TableLogic.save_table_final_records(tableobj)
    local game_records = tableobj.game_records

    local tablerecords = ""
	tablerecords = tablerecords .. game_records.table_uuid .. "_"           --桌子唯一id
    tablerecords = tablerecords .. game_records.table_type .. "_"           --桌子类型
	tablerecords = tablerecords .. game_records.create_user_rid .. "_"      --创建者rid
	tablerecords = tablerecords .. game_records.create_time .. "_"          --创建时间
    tablerecords = tablerecords .. game_records.delete_time .. "_"          --删除时间
	tablerecords = tablerecords .. game_records.start_time .. "_"           --第一局开始时间
    tablerecords = tablerecords .. game_records.end_time .. "_"             --最后一局结束时间
    tablerecords = tablerecords .. game_records.final_to_num .. "_"         --最终局数
    tablerecords = tablerecords .. game_records.delete_reason or 0          --删除原因
    
    --调用日志服务写到文件
	skynet.send(".gametablelog", "lua", "write",tablerecords)
end

--
--创建系统庄家
--
function TableLogic.gen_system_banker_info(tableobj)
    local banker_info = {}

    seatlogic.init_data(banker_info, -1)
    banker_info.rid = -1
    banker_info.real_rid = -1
    banker_info.is_banker = true
    banker_info.playerinfo.rolename = "小苏苏"
    banker_info.playerinfo.logo = "avator_71.jpg"
    banker_info.playerinfo.sex = 1
    banker_info.playerinfo.index = -1
    banker_info.playerinfo.coin = 500000
    banker_info.playerinfo.diamond = 500000
    banker_info.dobanker_round_num = 0   --做庄局数
    banker_info.last_win_score = 0       --上局输赢

    --从机器人节点获取系统庄信息
    local robotinfo = skynet.call(".robotmgr", "lua", "gen_system_banker_info")
    if robotinfo then
        banker_info.real_rid = robotinfo.rid
        banker_info.playerinfo.sex = robotinfo.sex
        banker_info.playerinfo.logo = robotinfo.logo
        banker_info.playerinfo.rolename = robotinfo.rolename
        banker_info.playerinfo.ip_addr = robotinfo.ip_addr
        banker_info.playerinfo.gps_addr = robotinfo.gps_addr
    end

    return banker_info
end

--
--获取游戏名（包括桌子类型)
--
function TableLogic.get_gamename(tableobj)
    local gamename = "yydb"
    if tableobj.table_type == YYDBTableType.TABLE_TYPE_COIN then
        gamename = gamename .. "_coin"
    elseif tableobj.table_type == YYDBTableType.TABLE_TYPE_DIAMOND then
        gamename = gamename .. "_diamond_" .. tostring(tableobj.conf.level_type)
    end
    return gamename
end

--
--获得当前代币数
--
function TableLogic.get_curmoney(seat)
    if not seat or not seat.playerinfo then
        return 0
    end

    local tableobj = service.table_data
    if tableobj.table_type == YYDBTableType.TABLE_TYPE_DIAMOND then
        return (seat.playerinfo.diamond or 0)
    elseif tableobj.table_type == YYDBTableType.TABLE_TYPE_COIN then
        return (seat.playerinfo.coin or 0)
    end
    return 0
end

--
--是否是金币桌
--
function TableLogic.is_cointable()
    if service.table_data.table_type == YYDBTableType.TABLE_TYPE_COIN then
        return true
    end
    return false
end

--
--是否是钻石桌
--
function TableLogic.is_diamondtable()
    if service.table_data.table_type == YYDBTableType.TABLE_TYPE_DIAMOND then
        return true
    end
    return false
end

--
--发送跑马灯
--
function TableLogic.send_horseracelamp(rolename, get_num)
	local horseconf = configdao.get_common_conf("horselampconf")
	if not horseconf or not horseconf[1] then return end
	local formatname = string.format(ELAMPCOLOR.GREEN, rolename)
	local formatnum = string.format(ELAMPCOLOR.RED, tostring(get_num))
	local horsestring = string.format(horseconf[1], formatname, EGameName, formatnum)
	skynet.pcall(cluster.send, "gatenode", ".router", "addpopmessage", horsestring)
end

--
--发送聊天消息
--
function TableLogic.send_tablechat(table_index, talkrid, msgbody, is_nodealy)
    if not is_nodealy then
        local delay = base.get_random(1,3)
        skynet.sleep(delay * 100)
    end
    skynet.pcall(cluster.send, "gatenode", ".router", "robot_tablechat", "yydb", table_index, talkrid, msgbody)
end

--
--生成随机码池子
--
function TableLogic.full_random_codes_pool(tableobj, codes_num)
    tableobj.all_random_codes_pool = {}
    local codes_num_ = codes_num
    if not codes_num_ or codes_num_ < 0 then
        codes_num_ = math.floor(tableobj.conf.total_bet_limit / 100) 
    end
    ---local gen_codes = yydbtool.gen_all_randomcodes(codes_num_)
    local gen_codes = yydbtool.gen_randomcodes()
    tableobj.all_random_codes_pool = tabletool.deepcopy(gen_codes)
end

function TableLogic.open_award_deal(tableobj, openaward_type)
    local ipairs_random_codes = {}
    for rid, value in pairs(tableobj.open_award_random_codes_pool) do
        table.insert(ipairs_random_codes, { rid = rid, get_code = value.get_code, bet_num = value.bet_num})
    end
    table.sort(ipairs_random_codes, function(first, second)
            if first.bet_num > second.bet_num then return true else return false end
        end)
    local function get_award_rid_by_weight(tableobj, ipairs_random_codes, is_player)
        local all_weight_value = 0
        if is_player == true then
            local all_players = {}
            for index, betitem in ipairs(ipairs_random_codes) do
                if betitem.bet_num then 
                    local seat = TableLogic.get_seat_by_rid(tableobj, betitem.rid)
                    if seat.is_robot == false then
                        all_weight_value = all_weight_value + betitem.bet_num
                        table.insert(all_players, betitem) 
                    end
                end
            end
            if #all_players == 0 then
                all_weight_value = 0
                for index, betitem in ipairs(ipairs_random_codes) do
                    if betitem.bet_num then all_weight_value = all_weight_value + betitem.bet_num end
                end
                local get_random_value = base.get_random(1, all_weight_value)
                ---filelog.sys_error("--------get_random_value-------", get_random_value)
                local get_index = 0
                for index, betitem in ipairs(ipairs_random_codes) do
                    if betitem.bet_num then
                        get_random_value = get_random_value - betitem.bet_num 
                        if get_random_value <= 0 then get_index = index break end
                    end
                end
                ---filelog.sys_error("------------get_index----------", get_index)
                return get_index
            else
                local get_random_value = base.get_random(1, all_weight_value)
                
                local get_index = 0
                for index, betitem in ipairs(all_players) do
                    if betitem.bet_num then
                        get_random_value = get_random_value - betitem.bet_num 
                        if get_random_value <= 0 then get_index = index break end
                    end
                end
                
                return get_index
            end
        else
            for index, betitem in ipairs(ipairs_random_codes) do
                if betitem.bet_num then all_weight_value = all_weight_value + betitem.bet_num end
            end
            local get_random_value = base.get_random(1, all_weight_value)
            
            local get_index = 0
            for index, betitem in ipairs(ipairs_random_codes) do
                if betitem.bet_num then
                    get_random_value = get_random_value - betitem.bet_num 
                    if get_random_value <= 0 then get_index = index break end
                end
            end
            
            return get_index
        end
    end
    if openaward_type == LotteryType.LOTTERY_TYPE_SYSTEM_WIN then
        ---系统必赢开奖,机器人中奖
        if #tableobj.all_beted_robot_codes > 0 then
            local get_index = base.get_random(1, #tableobj.all_beted_robot_codes)
            local award_code = table.remove(tableobj.all_beted_robot_codes, get_index)
            local get_award_rid = tableobj.rids_with_random_codes[award_code]
            local award_seat = TableLogic.get_seat_by_rid(tableobj, get_award_rid)
            if not award_seat then
                return false
            else
                tableobj.open_award_result.open_award_code = award_code
                tableobj.open_award_result.open_award_rid  = get_award_rid
                tableobj.open_award_result.open_award_rolename = award_seat.playerinfo.rolename
                tableobj.open_award_result.open_award_num = tableobj.cur_total_bet_num
                tableobj.open_award_result.open_logo = award_seat.playerinfo.logo
                tableobj.open_award_result.is_robot = award_seat.is_robot
                return true
            end
        else
            local len = #ipairs_random_codes
            if len <= 0 then
                --filelog.sys_error("------open_award_random_codes_pool length is 0------")
                return false
            end
            --local get_index = base.get_random(1, len)
            local get_index = get_award_rid_by_weight(tableobj, ipairs_random_codes, false)
            if get_index == 0 then return false end

            local award_code = ipairs_random_codes[get_index].get_code
            ---local award_code = table.remove(tableobj.open_award_random_codes_pool[YYDBClassPool.FIRST_CLASS], get_index)
            local get_award_rid = tableobj.rids_with_random_codes[award_code]
            local award_seat = TableLogic.get_seat_by_rid(tableobj, get_award_rid)
            if not award_seat then
                return false
            else
                tableobj.open_award_result.open_award_code = award_code
                tableobj.open_award_result.open_award_rid  = get_award_rid
                tableobj.open_award_result.open_award_rolename = award_seat.playerinfo.rolename
                tableobj.open_award_result.open_award_num = tableobj.cur_total_bet_num
                tableobj.open_award_result.open_logo = award_seat.playerinfo.logo
                tableobj.open_award_result.is_robot = award_seat.is_robot
                return true
            end
        end
    elseif openaward_type == LotteryType.LOTTERY_TYPE_SYSTEM_LOSE then
        ---系统必输开奖,玩家中奖
        local len = #ipairs_random_codes
        if len <= 0 then
            --filelog.sys_error("------open_award_random_codes_pool length is 0------")
            return false
        end
        --local get_index = base.get_random(1, len)
        local get_index = get_award_rid_by_weight(tableobj, ipairs_random_codes, true)
        if get_index == 0 then return false end
        local award_code = ipairs_random_codes[get_index].get_code
        local get_award_rid = tableobj.rids_with_random_codes[award_code]
        local award_seat = TableLogic.get_seat_by_rid(tableobj, get_award_rid)
        if not award_seat then
            return false
        else
            tableobj.open_award_result.open_award_code = award_code
            tableobj.open_award_result.open_award_rid  = get_award_rid
            tableobj.open_award_result.open_award_rolename = award_seat.playerinfo.rolename
            tableobj.open_award_result.open_award_num = tableobj.cur_total_bet_num
            tableobj.open_award_result.open_logo = award_seat.playerinfo.logo
            tableobj.open_award_result.is_robot = award_seat.is_robot
            return true
        end
    elseif openaward_type == LotteryType.LOTTERY_TYPE_NORMAL then
        ---随机开奖
        local len = #ipairs_random_codes
        if len <= 0 then
            ---filelog.sys_error("------open_award_random_codes_pool length is 0------")
            return false
        end
        local get_index = get_award_rid_by_weight(tableobj, ipairs_random_codes, false)
        if get_index == 0 then return false end

        local award_code = ipairs_random_codes[get_index].get_code
        local get_award_rid = tableobj.rids_with_random_codes[award_code]
        local award_seat = TableLogic.get_seat_by_rid(tableobj, get_award_rid)
        if not award_seat then
            return false
        else
            tableobj.open_award_result.open_award_code = award_code
            tableobj.open_award_result.open_award_rid  = get_award_rid
            tableobj.open_award_result.open_award_rolename = award_seat.playerinfo.rolename
            tableobj.open_award_result.open_award_num = tableobj.cur_total_bet_num
            tableobj.open_award_result.open_logo = award_seat.playerinfo.logo
            tableobj.open_award_result.is_robot = award_seat.is_robot
            return true
        end
    end
end

function TableLogic.getallrecords(tableobj, rid, request, seat)
    
    local all_records = {}

    local from_record_list = tabletool.deepcopy(tableobj.history_record_lists)

    table.sort(from_record_list, function(first, second) 
                if first.open_award_time > second.open_award_time then
                    return true
                else
                    return false
                end
        end)
    for key, record in ipairs(from_record_list) do
        --[[
            message recorditem {
                optional int32  open_time           = 1;
                optional string qishu               = 2;        //当日期数
                optional string getaward_code       = 3;        //获奖随机码
                optional int32  rid                 = 4;        // 获奖玩家rid
                optional string rolename            = 5;        //获奖玩家名字 
                optional int32  award_num           = 6;        //获奖金额
                optional string logo                = 7;        // 玩家logo
                optional string mycode              = 8;        //你的随机码(这一局游戏购买的随机码)
            }
        --]]
        local base_records = {
            open_time = record.open_award_time,
            qishu = tostring(record.today_times),
            getaward_code = record.getaward_code,
            rid = record.rid,
            rolename = record.rolename,
            award_num = record.award_num,
            logo = record.logo,
            mycode = "",
        }
        if  record.all_player_codes[rid] ~= nil then
            base_records.mycode = record.all_player_codes[rid]
        end
        if #all_records < 10 then
            table.insert(all_records, base_records)
        end
    end
    ----filelog.sys_error("-------------TableLogic.getallrecords---------", rid, request, all_records)
    return { recorditems = all_records }
end

function TableLogic.getrecordmycodes(tableobj, rid, request, seat)
    local all_my_codes = {}
    if not request.open_award_time then
        return { get_codes_list = all_my_codes }
    end
    for i, record in ipairs(tableobj.history_record_lists) do
        if request.open_award_time == record.open_award_time then
            for key, code in pairs(record.all_player_codes[rid]) do
                 table.insert(all_my_codes, tostring(code))
            end
        end
    end
    return { get_codes_list = all_my_codes }
end

return TableLogic